using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.ServiceModel.Syndication;
using System.Web.Mvc;
using System.Web.Routing;
using System.Xml;
using Core.BOL;
using Core.DAL;
using Core.Extentions;

namespace ScoutNET.Controllers
{
    public class RSSController : ApplicationController
    {
        private NewsRepository n = new NewsRepository();
        private SectionRepository sr = new SectionRepository();
        private ConvocRepository c = new ConvocRepository();

        public ActionResult Index()
        {
            ViewData["PageTitle"] = Resources.Pages_RSS_Title;
            ViewData["PageDescription"] = Resources.Pages_RSS_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Pages_RSS_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            return View("RSS");
        }

        [OutputCache(CacheProfile = "RSS")]
        public FileStreamResult Feed(string systemName, string target)
        {
            List<tSite_New> lNews = new List<tSite_New>();
            lNews = (sr.IsAdministrativeSection(systemName)) ? n.GetNews(0, 30) : n.GetNewsBySectionName(systemName, 0, 30);
            
            List<SyndicationItem> items = new List<SyndicationItem>();
            foreach (tSite_New news in lNews)
	        {
                Uri u = null;
                string text = string.Empty;
                if (target != null && target.ToLower() == "facebook")
                {
                    string url = ConfigurationManager.AppSettings["SiteUrl"] + Url.Action("Details", new { 
                        controller = "News",
                        systemName = news.SystemName.UppercaseFirst(),
                        Title = news.Title.ParseUrl(),
                        ID = news.ID,
                        utm_source = "Facebook",
                        utm_medium = "Alt link",
                        utm_campaign = "rss"
                    });
                    u = new Uri(url);
                    Uri uSrc = new Uri(ConfigurationManager.AppSettings["SiteUrl"]);

                    text = news.News.AddUrlInHref(u).AddUrlInSrc(uSrc);
                }
                else
                {
                    string url = ConfigurationManager.AppSettings["SiteUrl"] + Url.Action("Details", new
                    {
                        controller = "News",
                        systemName = news.SystemName.UppercaseFirst(),
                        Title = news.Title.ParseUrl(),
                        ID = news.ID
                    });
                    u = new Uri(url);
                    Uri uSrc = new Uri(ConfigurationManager.AppSettings["SiteUrl"]);

                    text = news.News.AddUrlInHref(u).AddUrlInSrc(uSrc);
                }
                items.Add(new SyndicationItem(news.Title, text, u, news.ID.ToString(), news.InsertDate));
	        }

            string section = sr.GetSectionNameBySystemName(systemName);
            SyndicationFeed feed = new SyndicationFeed(ConfigurationManager.AppSettings["SiteName"] + " - " + section, section, Request.Url, items);

            Rss20FeedFormatter formatter = new Rss20FeedFormatter(feed);

            MemoryStream ms = new MemoryStream();
            using (XmlWriter writer = XmlWriter.Create(ms, new XmlWriterSettings { OmitXmlDeclaration = false }))
            {
                formatter.WriteTo(writer);
            }
            ms.Position = 0;

            return new FileStreamResult(ms, "application/rss+xml");
            
        }

        [OutputCache(CacheProfile = "RSS")]
        public FileStreamResult Convoc()
        {
            List<tSite_Convoc> lConvoc = c.GetAllConvoc(0,10);
            List<SyndicationItem> items = new List<SyndicationItem>();

            foreach (tSite_Convoc convoc in lConvoc)
            {
                string url = ConfigurationManager.AppSettings["SiteUrl"] + Url.Action("Detail", new
                {
                    controller = "Convoc",
                    systemName = convoc.SystemName.UppercaseFirst(),
                    ID = convoc.ID
                });
                Uri u = new Uri(url);
                Uri uSrc = new Uri(ConfigurationManager.AppSettings["SiteUrl"]);

                string text = convoc.Convoc.AddUrlInHref(u).AddUrlInSrc(uSrc);

                items.Add(new SyndicationItem(
                    "Convoc " + convoc.SectionName.ToLower() + " du " + convoc.StartDate.ToString("dd/MM/yyyy") + " au " + convoc.EndDate.ToString("dd/MM/yyyy")
                    , text
                    , u
                    , convoc.ID.ToString()
                    , convoc.InsertDate));
                
            }

            SyndicationFeed feed = new SyndicationFeed(ConfigurationManager.AppSettings["SiteName"], string.Empty, Request.Url, items);

            Atom10FeedFormatter formatter = new Atom10FeedFormatter(feed);
            using (MemoryStream ms = new MemoryStream())
            {
                using (XmlWriter writer = XmlWriter.Create(ms, new XmlWriterSettings { OmitXmlDeclaration = false }))
                {
                    formatter.WriteTo(writer);
                }
                ms.Position = 0;

                return new FileStreamResult(ms, "application/rss+xml");
            }
        }
    }
}
